package com.ctg.behavior.calc.impala.transfer.usergroups;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.ctg.behavior.calc.common.CtSQLParam;
import com.ctg.behavior.calc.impala.CtSQLTransfer;
import com.ctg.behavior.calc.impala.builder.userlist.CtUGULReportBuilder;
import com.ctg.behavior.calc.impala.report.userlist.CtCalcUGULReport;
import com.ctg.behavior.calc.impala.transfer.userlist.CtUGUserListTransfer;
import com.ctg.behavior.common.calc.CtCalc;
import com.ctg.behavior.common.usergroups.CtUGCalcBody;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class CtUGTransfer implements CtSQLTransfer {

	@Autowired
	private CtUGULReportBuilder ugulReportBuilder;
	@Autowired
	private CtUGUserListTransfer ugUserListTransfer;

	/******************************************************
	 * @apiNote:
	 */
	@Override
	public String doTransfer(CtCalc calcObject, CtSQLParam sqlParam) {

		if (!(calcObject instanceof CtUGCalcBody)) {
			log.warn("calcObject is not CtUGCalcBody, class={}", calcObject.getClass());
			return "";
		}
		CtUGCalcBody ugCalcBody = (CtUGCalcBody) calcObject;
		log.info("CalcBody={}", JSON.toJSONString(ugCalcBody));

		CtCalcUGULReport ugulReport = ugulReportBuilder.doBuilder(ugCalcBody);
		log.info("ugulReport={}", JSON.toJSONString(ugulReport));

		StringBuilder impalaSQL = new StringBuilder();

		impalaSQL.append(" SELECT COUNT(*) AS total FROM ( ");
		// 执行列表SQL生成器
		String sqlUserList = ugUserListTransfer.doTransfer(ugulReport, sqlParam);
		// 移除最后的ORDER BY, 及LIMIT, 不能移除GROUP BY
		int index = sqlUserList.indexOf("ORDER");
		if (index < 0) {
			index = sqlUserList.indexOf("LIMIT");
		}
		if (index > 0) {
			sqlUserList = sqlUserList.substring(0, index);
		}
		impalaSQL.append(sqlUserList);
		impalaSQL.append(" ) TP0 ");
		impalaSQL.append(" WHERE TP0.userId is not null ");

		String retSQL = impalaSQL.toString();
		log.info("CalcSQL={}", retSQL);

		return retSQL;
	}

}
